package com.uzai.console.service.fd.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.dto.fadan.FdFollowGroupTaskCacheDto;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.fd.fddeviceplan.FdDevicePlanIdDto;
import com.uzai.console.dto.fd.fdfollowgroupconfig.FdFollowGroupConfigDto;
import com.uzai.console.dto.fd.fdfollowgroupconfig.FdFollowGroupConfigIdDto;
import com.uzai.console.dto.fd.fdfollowgroupconfig.FdFollowGroupConfigQuery;
import com.uzai.console.dto.fd.fdfollowgroupconfig.FdFollowGroupConfigStatusDto;
import com.uzai.console.entity.*;
import com.uzai.console.enums.SmsType;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.fd.FdDevicePlanService;
import com.uzai.console.service.fd.FdFollowGroupConfigService;
import com.uzai.console.service.feign.UzaiImClientFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.vo.fd.fddeviceplan.FdDevicePlanVo;
import com.uzai.console.vo.fd.fdfollowgroupconfig.FdFollowGroupConfigVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 发单跟发采集群配置
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class FdFollowGroupConfigServiceImpl implements FdFollowGroupConfigService {

    Logger logger = LoggerFactory.getLogger(FdFollowGroupConfigServiceImpl.class);

    @Autowired
    private FdFollowGroupConfigMapper fdFollowGroupConfigMapper;
    @Autowired
    private FdFollowGroupMapper fdFollowGroupMapper;
    @Autowired
    private UzaiImClientFeignService uzaiImClientFeignService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private FdDevicePlanMapper fdDevicePlanMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private FdDevicePlanGroupMapper fdDevicePlanGroupMapper;
    @Autowired
    private WxqGroupManagePlanMapper wxqGroupManagePlanMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private WxqWorkGroupManagePlanMapper wxqWorkGroupManagePlanMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private FdDevicePlanService fdDevicePlanService;

    /**
     * 查询发单跟发配置列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdFollowGroupConfigQuery
     * @return null
     */
    public Page<FdFollowGroupConfigVo> findFdFollowGroupConfigList(FdFollowGroupConfigQuery fdFollowGroupConfigQuery){
        //新建返回到页面的LIST对象
        List<FdFollowGroupConfigVo> fdFollowGroupConfigPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<FdFollowGroupConfig> page = new Page<>();
        fdFollowGroupConfigQuery.convert(page);
        List<FdFollowGroupConfig> fdFollowGroupConfigList =  fdFollowGroupConfigMapper.findByList(page, fdFollowGroupConfigQuery);
        if(fdFollowGroupConfigList != null && fdFollowGroupConfigList.size() > 0){
            for (FdFollowGroupConfig fdFollowGroupConfig : fdFollowGroupConfigList){
                FdFollowGroupConfigVo fdFollowGroupConfigPageVo = new FdFollowGroupConfigVo();
                BeanUtils.copyProperties(fdFollowGroupConfig, fdFollowGroupConfigPageVo);

                //设备方案名称
                if(fdFollowGroupConfig.getFdDevicePlanId() != null){
                    FdDevicePlan fdDevicePlan = fdDevicePlanMapper.selectById(fdFollowGroupConfig.getFdDevicePlanId(), fdFollowGroupConfig.getMerId());
                    if(fdDevicePlan != null){
                        fdFollowGroupConfigPageVo.setFdDevicePlanName(fdDevicePlan.getName());
                    }
                }

                //封装关键词过滤
                if(StringUtils.isNotBlank(fdFollowGroupConfig.getIgnore())){
                    List<String> ignoreList = JSONObject.parseArray(fdFollowGroupConfig.getIgnore(), String.class);
                    fdFollowGroupConfigPageVo.setIgnoreList(ignoreList);
                }

                //采集群信息
                if(StringUtils.isNotBlank(fdFollowGroupConfig.getGroupWxid())){
                    FdFollowGroup fdFollowGroup = fdFollowGroupMapper.selectByWxid(fdFollowGroupConfig.getGroupWxid());
                    if(fdFollowGroup != null){
                        fdFollowGroupConfigPageVo.setGroupNickName(fdFollowGroup.getNickName());
                    }
                }

                fdFollowGroupConfigPageVoList.add(fdFollowGroupConfigPageVo);
            }
        }
        //返回到页面分页对象
        Page<FdFollowGroupConfigVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(fdFollowGroupConfigPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询发单跟发配置详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdFollowGroupConfigIdDto
     * @return null
     */
    public FdFollowGroupConfigVo findFdFollowGroupConfig(FdFollowGroupConfigIdDto fdFollowGroupConfigIdDto){
        if(fdFollowGroupConfigIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        FdFollowGroupConfig fdFollowGroupConfig = fdFollowGroupConfigMapper.selectById(fdFollowGroupConfigIdDto.getId(), fdFollowGroupConfigIdDto.getMerId());

        if(fdFollowGroupConfig == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该发单跟发配置不存在");
        }

        FdFollowGroupConfigVo fdFollowGroupConfigVo = new FdFollowGroupConfigVo();
        BeanUtils.copyProperties(fdFollowGroupConfig, fdFollowGroupConfigVo);

        //封装关键词过滤
        if(StringUtils.isNotBlank(fdFollowGroupConfig.getIgnore())){
            List<String> ignoreList = JSONObject.parseArray(fdFollowGroupConfig.getIgnore(), String.class);
            fdFollowGroupConfigVo.setIgnoreList(ignoreList);
        }

        //采集群信息
        if(StringUtils.isNotBlank(fdFollowGroupConfig.getGroupWxid())){
            FdFollowGroup fdFollowGroup = fdFollowGroupMapper.selectByWxid(fdFollowGroupConfig.getGroupWxid());
            if(fdFollowGroup != null){
                fdFollowGroupConfigVo.setGroupNickName(fdFollowGroup.getNickName());
            }
        }

        return fdFollowGroupConfigVo;
    }

    /**
     * 添加发单跟发配置
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdFollowGroupConfigDto
     * @return null
     */
    public void addFdFollowGroupConfig(FdFollowGroupConfigDto fdFollowGroupConfigDto){

        Long merId = fdFollowGroupConfigDto.getMerId();

        if(fdFollowGroupConfigDto.getFdDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }


        if(fdFollowGroupConfigDto.getFdDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        //查询该设备方案所有群信息
        FdDevicePlanIdDto pyqDevicePlanIdDto = new FdDevicePlanIdDto();
        pyqDevicePlanIdDto.setMerId(fdFollowGroupConfigDto.getMerId());
        pyqDevicePlanIdDto.setId(fdFollowGroupConfigDto.getFdDevicePlanId());
        FdDevicePlanVo fdDevicePlan = fdDevicePlanService.findFdDevicePlan(pyqDevicePlanIdDto);
        if(fdDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "设备方案不存在");
        }
        //查询该设备方案包含的群类型
        Set<String> deviceTypeList = fdDevicePlan.getDeviceTypeList();
        if(deviceTypeList != null && deviceTypeList.contains(DeviceTypeEnum.TIKTOK.getKey())){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该抖音群设备方案目前不支持跟发功能");
        }

        if(StringUtils.isBlank(fdFollowGroupConfigDto.getGroupWxid())){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入采集群微信id");
        }

        FdFollowGroup fdFollowGroup = fdFollowGroupMapper.selectByWxid(fdFollowGroupConfigDto.getGroupWxid());

        if(fdFollowGroup == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "采集群不存在");
        }

        if(fdFollowGroup.getStatus().intValue() != 1){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "此采集群已经关闭，不能添加跟发");
        }

        Integer now = DateUtil.getNowTime();
        FdFollowGroupConfig fdFollowGroupConfig = new FdFollowGroupConfig();
        fdFollowGroupConfig.setId(IdWorker.getId());
        fdFollowGroupConfig.setName(fdFollowGroupConfigDto.getName());
        fdFollowGroupConfig.setMerId(fdFollowGroupConfigDto.getMerId());
        fdFollowGroupConfig.setGroupWxid(fdFollowGroupConfigDto.getGroupWxid());
        fdFollowGroupConfig.setFdDevicePlanId(fdFollowGroupConfigDto.getFdDevicePlanId());
        fdFollowGroupConfig.setStatus(0); //默认关闭
        fdFollowGroupConfig.setIgnore(Tools.getStrEmpty(JSONObject.toJSONString(fdFollowGroupConfigDto.getIgnoreList())));
        fdFollowGroupConfig.setImgSecret(Tools.getInteger(fdFollowGroupConfigDto.getImgSecret()));
        fdFollowGroupConfig.setEmoji(Tools.getInteger(fdFollowGroupConfigDto.getEmoji()));
        fdFollowGroupConfig.setTurnlink(Tools.getInteger(fdFollowGroupConfigDto.getTurnlink()));
        fdFollowGroupConfig.setLimitTimeStart(fdFollowGroupConfigDto.getLimitTimeStart());
        fdFollowGroupConfig.setLimitTimeEnd(fdFollowGroupConfigDto.getLimitTimeEnd());
        fdFollowGroupConfig.setCreateTime(now);
        fdFollowGroupConfig.setUpdateTime(now);
        fdFollowGroupConfigMapper.insert(fdFollowGroupConfig);
    }

    /**
     * 修改发单跟发配置
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdFollowGroupConfigDto
     * @return null
     */
    @Transactional
    public void updateFdFollowGroupConfig(FdFollowGroupConfigDto fdFollowGroupConfigDto){

        Long merId = fdFollowGroupConfigDto.getMerId();

        if(fdFollowGroupConfigDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if(fdFollowGroupConfigDto.getFdDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }
        //查询该设备方案所有群信息
        FdDevicePlanIdDto pyqDevicePlanIdDto = new FdDevicePlanIdDto();
        pyqDevicePlanIdDto.setMerId(fdFollowGroupConfigDto.getMerId());
        pyqDevicePlanIdDto.setId(fdFollowGroupConfigDto.getFdDevicePlanId());
        FdDevicePlanVo fdDevicePlan = fdDevicePlanService.findFdDevicePlan(pyqDevicePlanIdDto);
        if(fdDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "设备方案不存在");
        }

        if(StringUtils.isBlank(fdFollowGroupConfigDto.getGroupWxid())){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入采集群微信id");
        }

        FdFollowGroup fdFollowGroup = fdFollowGroupMapper.selectByWxid(fdFollowGroupConfigDto.getGroupWxid());

        if(fdFollowGroup == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "采集群不存在");
        }

        if(fdFollowGroup.getStatus().intValue() != 1){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "此采集群已经关闭，不能添加跟发");
        }


        FdFollowGroupConfig fdFollowGroupConfig = fdFollowGroupConfigMapper.selectById(fdFollowGroupConfigDto.getId(), fdFollowGroupConfigDto.getMerId());
        if(fdFollowGroupConfig == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该跟发配置任务不存在");
        }

        if(Tools.getInteger(fdFollowGroupConfig.getStatus()).intValue() == 1){ //启动状态不能编辑
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该任务正在启动中，请先关闭之后再编辑");
        }

        fdFollowGroupConfig.setMerId(fdFollowGroupConfigDto.getMerId());
        fdFollowGroupConfig.setName(fdFollowGroupConfigDto.getName());
        fdFollowGroupConfig.setGroupWxid(fdFollowGroupConfigDto.getGroupWxid());
        fdFollowGroupConfig.setFdDevicePlanId(fdFollowGroupConfigDto.getFdDevicePlanId());
        fdFollowGroupConfig.setIgnore(Tools.getStrEmpty(JSONObject.toJSONString(fdFollowGroupConfigDto.getIgnoreList())));
        fdFollowGroupConfig.setImgSecret(Tools.getInteger(fdFollowGroupConfigDto.getImgSecret()));
        fdFollowGroupConfig.setEmoji(Tools.getInteger(fdFollowGroupConfigDto.getEmoji()));
        fdFollowGroupConfig.setTurnlink(Tools.getInteger(fdFollowGroupConfigDto.getTurnlink()));
        fdFollowGroupConfig.setLimitTimeStart(fdFollowGroupConfigDto.getLimitTimeStart());
        fdFollowGroupConfig.setLimitTimeEnd(fdFollowGroupConfigDto.getLimitTimeEnd());
        Integer now = DateUtil.getNowTime();
        fdFollowGroupConfig.setUpdateTime(now);

        fdFollowGroupConfigMapper.updateById(fdFollowGroupConfig);

    }

    /**
     * 删除
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdFollowGroupConfigIdDto
     * @return null
     */
    @Transactional
    public void deleteFdFollowGroupConfig(FdFollowGroupConfigIdDto fdFollowGroupConfigIdDto){
        if(fdFollowGroupConfigIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        FdFollowGroupConfig fdFollowGroupConfig = fdFollowGroupConfigMapper.selectById(fdFollowGroupConfigIdDto.getId(), fdFollowGroupConfigIdDto.getMerId());

        if(fdFollowGroupConfig == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此跟发配置不存在");
        }
        //删除
        fdFollowGroupConfigMapper.deleteById(fdFollowGroupConfigIdDto.getId(), fdFollowGroupConfigIdDto.getMerId());

        //删除缓存
        updateFdFollowGroupTaskCache(fdFollowGroupConfig.getGroupWxid());
    }


    /**
     * 设置是否开启
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdFollowGroupConfigStatusDto
     * @return null
     */
    @Transactional
    public void updateStatus(FdFollowGroupConfigStatusDto fdFollowGroupConfigStatusDto){

        if(fdFollowGroupConfigStatusDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        FdFollowGroupConfig fdFollowGroupConfig = fdFollowGroupConfigMapper.selectById(fdFollowGroupConfigStatusDto.getId(), fdFollowGroupConfigStatusDto.getMerId());

        if(fdFollowGroupConfig == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此跟发配置不存在");
        }

        if(StringUtils.isBlank(fdFollowGroupConfig.getGroupWxid())){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入采集群群wxid");
        }
        FdFollowGroup fdFollowGroup = fdFollowGroupMapper.selectByWxid(fdFollowGroupConfig.getGroupWxid());

        if(fdFollowGroup == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "采集群不存在");
        }

        if(fdFollowGroup.getStatus().intValue() != 1){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "此采集群已经关闭，不能启动跟发配置任务");
        }

        fdFollowGroupConfig.setStatus(Tools.getInteger(fdFollowGroupConfigStatusDto.getStatus()));

        //修改状态
        int i = fdFollowGroupConfigMapper.updateStatusById(fdFollowGroupConfig);
        //保存成功，则更新该采集群得所有开启的跟发任务缓存
        if(i==1){
            //分布式锁
            String groupWxid =  fdFollowGroupConfig.getGroupWxid();
            String key = "updateFdFollowGroupTaskCache_" + groupWxid;
            try{
                //获取存在redis中的验证码
                Object object = redisTemplate.opsForValue().get(key);
                if(object != null){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "网络繁忙！");
                }
                //设置10秒等待期
                redisTemplate.opsForValue().set(key, groupWxid , 10, TimeUnit.SECONDS);
                //更新该采集群得所有开启的跟发任务缓存
                updateFdFollowGroupTaskCache(fdFollowGroupConfig.getGroupWxid());
                //操作完成，删除缓存
                redisTemplate.delete(key);
            }catch (Exception e){
                logger.error("--修改采集群配置缓存--err={}", e.getMessage());
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开启失败:"+e.getMessage());
            }finally {
                //操作完成，删除缓存
                redisTemplate.delete(key);
            }
        }else{
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络延迟");
        }
    }
    
    /**
     * 刷新采集群跟发配置缓存
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupWxid
     * @return null
     */
    public void updateFdFollowGroupTaskCache(String groupWxid){

        if(StringUtils.isBlank(groupWxid)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群微信id不能二为空");
        }

        List<FdFollowGroupTaskCacheDto> fdFollowGroupTaskCacheDtoList = new ArrayList<>();

        //查询该采集群所有的开启的跟发任务
        FdFollowGroupConfigQuery fdFollowGroupConfigQuery = new FdFollowGroupConfigQuery();
        fdFollowGroupConfigQuery.setGroupWxid(groupWxid);
        fdFollowGroupConfigQuery.setStatus(1);//开启状态
        List<FdFollowGroupConfig> fdFollowGroupConfigList = fdFollowGroupConfigMapper.findByList(fdFollowGroupConfigQuery);
        if(fdFollowGroupConfigList != null && fdFollowGroupConfigList.size() > 0){
            for (FdFollowGroupConfig fdFollowGroupConfig : fdFollowGroupConfigList) {
                FdDevicePlan fdDevicePlan = fdDevicePlanMapper.selectById(fdFollowGroupConfig.getFdDevicePlanId(), fdFollowGroupConfig.getMerId());
                if(fdDevicePlan != null) {
                    //查询该配置方案关联的群信息
                    List<FdDevicePlanGroup> fdDevicePlanGroupList = fdDevicePlanGroupMapper.findByListByFdDevicePlanId(fdDevicePlan.getId(), fdDevicePlan.getMerId());
                    if (fdDevicePlanGroupList != null && fdDevicePlanGroupList.size() > 0) {
                        for (FdDevicePlanGroup fdDevicePlanGroup : fdDevicePlanGroupList) {

                            FdFollowGroupTaskCacheDto fdFollowGroupTaskCacheDto = new FdFollowGroupTaskCacheDto();

                            //判断此群的配置方案是否开启了群发功能，如果未开启，则抛出异常
//                            if (fdDevicePlanGroup.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())) {//个人微信
//                                //是否配置了群管理方案
//                                WxqGroupManagePlan wxqGroupManagePlan = wxqGroupManagePlanMapper.selectByWxidAndDeviceUniqueIdAndMerId(fdDevicePlanGroup.getWxid(), fdDevicePlanGroup.getDeviceUniqueId(), fdDevicePlanGroup.getMerId());
//                                if (wxqGroupManagePlan == null) {
//                                    continue;
//                                }
//                                //查找配置方案
//                                ConfigPlan configPlan = configPlanMapper.selectById(wxqGroupManagePlan.getManagePlanId(), fdDevicePlan.getMerId());
//                                if (configPlan == null) {
//                                    continue;
//                                }
//                                //查找插件
//                                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdDevicePlan.getMerId());
//                                if (sysPlugin == null) {
//                                    continue;
//                                }
//                                JSONObject jsonObject = null;
//                                try {
//                                    jsonObject = JSONObject.parseObject(sysPlugin.getData());
//                                } catch (Exception e) {
//                                    continue;
//                                }
//
//                                //该群未找到配置方案对应插件信息
//                                if (jsonObject == null) {
//                                   continue;
//                                }
//
//                                //判断该群管理方案未开启社群群发功能
//                                Integer fdSwitch = jsonObject.getInteger("fdSwitch");
//                                if (fdSwitch == null || fdSwitch.intValue() != 1) { //未开启社群群发功能
//                                    continue;
//                                }
//                            } else {//企业微信
//                                //是否配置了群管理方案
//                                WxqWorkGroupManagePlan wxqWorkGroupManagePlan = wxqWorkGroupManagePlanMapper.selectByGroupIdAndDeviceUniqueIdAndMerId(fdDevicePlanGroup.getWxid(), fdDevicePlanGroup.getDeviceUniqueId(), fdDevicePlanGroup.getMerId());
//                                if (wxqWorkGroupManagePlan == null) {
//                                   continue;
//                                }
//                                //查找配置方案
//                                ConfigPlan configPlan = configPlanMapper.selectById(wxqWorkGroupManagePlan.getManagePlanId(), fdDevicePlanGroup.getMerId());
//                                if (configPlan == null) {
//                                   continue;
//                                }
//                                //查找插件
//                                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdDevicePlanGroup.getMerId());
//                                if (sysPlugin == null) {
//                                    continue;
//                                }
//
//                                JSONObject jsonObject = null;
//
//                                try {
//                                    jsonObject = JSONObject.parseObject(sysPlugin.getData());
//                                } catch (Exception e) {
//                                   continue;
//                                }
//
//                                //该群未找到配置方案对应插件信息
//                                if (jsonObject == null) {
//                                    continue;
//                                }
//
//                                //判断该群管理方案未开启社群群发功能
//                                Integer fdSwitch = jsonObject.getInteger("fdSwitch");
//                                if (fdSwitch == null || fdSwitch.intValue() != 1) { //未开启社群群发功能
//                                   continue;
//                                }
//                            }

                            //验证发送消息机器人存不存在
                            Device device_groupSendMsg = deviceService.findDeviceInfoByDeviceUniqueId(fdDevicePlanGroup.getGroupSendDeviceUniqueId(),fdDevicePlanGroup.getDeviceType(),fdDevicePlanGroup.getMerId());
                            if(device_groupSendMsg == null){
                                continue;
                            }

                            //开启了群发功能，封装缓存信息
                            Long tbTokenId = null;
                            String tbPid = "";
                            String tbRid = "";
                            //淘口令前缀
                            String pwdpres = "";
                            //淘口令后缀
                            String pwdsufs = "";

                            Long jdTokenId = null;
                            Long pddTokenId = null;
                            Long vphTokenId = null;
                            Long dyTokenId = null;
                            Integer pddTokenType = null;
                            Integer dyTokenType = null;

                            //中间页参数
                            Integer middlePageType = null;
                            String middlePageUrl = "";
                            //机器人身上的配置方案
                            ConfigPlan configPlan = null;

                            //1-从配置方案的群相关设置中获取联盟
                            //淘宝平台
                            tbTokenId = fdDevicePlanGroup.getTbTokenId();
                            tbPid = fdDevicePlanGroup.getTbPid();
                            tbRid = fdDevicePlanGroup.getTbRid();
                            middlePageType = fdDevicePlanGroup.getMiddlePageType();
                            middlePageUrl = fdDevicePlanGroup.getMiddlePageUrl();
                            pwdpres = fdDevicePlanGroup.getPwdpres();
                            pwdsufs = fdDevicePlanGroup.getPwdsufs();
                            //京东平台
                            jdTokenId = fdDevicePlanGroup.getJdTokenId();
                            //拼多多平台
                            pddTokenType = fdDevicePlanGroup.getPddTokenType();
                            if(pddTokenType != null && pddTokenType.intValue() == 1){ //推老板共享联盟
                                pddTokenId = fdDevicePlanGroup.getPddTlbTokenId();
                            }else{
                                pddTokenId = fdDevicePlanGroup.getPddTokenId();
                            }
                            //唯品会
                            vphTokenId = fdDevicePlanGroup.getVphTokenId();
                            //抖音
                            dyTokenType = fdDevicePlanGroup.getDyTokenType();
                            if(dyTokenType != null && dyTokenType.intValue() == 1){ //推老板共享联盟
                                dyTokenId = fdDevicePlanGroup.getDyTlbTokenId();
                            }else{
                                dyTokenId = fdDevicePlanGroup.getDyTokenId();
                            }

                            //2-如果群相关设置中没有设置，则从配置方案中获取
                            if(fdDevicePlan.getTokenSet() != null && fdDevicePlan.getTokenSet().intValue() == 1) { //自己设置联盟
                                //淘宝平台
                                if(tbTokenId == null){
                                    //从配置方案中获取
                                    tbTokenId = fdDevicePlan.getTbTokenId();
                                }
                                if(StringUtils.isBlank(tbPid)){
                                    tbPid = fdDevicePlan.getTbPid();
                                }
                                if(StringUtils.isBlank(tbRid)){
                                    tbRid = fdDevicePlan.getTbRid();
                                }

                                if(middlePageType == null){
                                    middlePageType = fdDevicePlan.getMiddlePageType();
                                }

                                if(StringUtils.isBlank(middlePageUrl)){
                                    middlePageUrl = fdDevicePlan.getMiddlePageUrl();
                                }

                                if(StringUtils.isBlank(pwdpres)){
                                    pwdpres = fdDevicePlan.getPwdpres();
                                }

                                if(StringUtils.isBlank(pwdsufs)){
                                    pwdsufs = fdDevicePlan.getPwdsufs();
                                }

                                //京东平台
                                if(jdTokenId == null){
                                    //从配置方案中获取
                                    jdTokenId = fdDevicePlan.getJdTokenId();
                                }
                                //拼多多平台
                                pddTokenType = fdDevicePlan.getPddTokenType();
                                if(pddTokenType != null && pddTokenType.intValue() == 1){ //推老板共享联盟
                                    pddTokenId = fdDevicePlan.getPddTlbTokenId();
                                }else{
                                    pddTokenId = fdDevicePlan.getPddTokenId();
                                }
                                //唯品会
                                if(vphTokenId == null){
                                    //从配置方案中获取
                                    vphTokenId = fdDevicePlan.getVphTokenId();
                                }
                                //抖音
                                dyTokenType = fdDevicePlan.getDyTokenType();
                                if(dyTokenType != null && dyTokenType.intValue() == 1){ //推老板共享联盟
                                    dyTokenId = fdDevicePlan.getDyTlbTokenId();
                                }else{
                                    dyTokenId = fdDevicePlan.getDyTokenId();
                                }
                            }

                            //3-如果联盟信息或者中间页还为空，则从群管理配置的机器身上获取
                            //淘宝平台
                            if(tbTokenId == null){
                                //查询当前群内发送消息机器人
                                if(configPlan == null){
                                    configPlan = configPlanMapper.selectById(device_groupSendMsg.getConfigId(), device_groupSendMsg.getMerId());
                                }
                                if(configPlan != null){
                                    //淘宝商品不从机器人配置方案中获取联盟，淘宝商品转链走导购联盟
                                    if(false){
                                        JSONObject jsonObject_tb = JSONObject.parseObject(configPlan.getTbAccountId());
                                        if(jsonObject_tb != null) {
                                            JSONArray jsonArray = jsonObject_tb.getJSONArray("tokens");
                                            if (jsonArray != null && jsonArray.size() > 0) {
                                                JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                                                String tokenIds = jsonObject.getString("tokenIds");
                                                List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                                                if (tokenList != null && tokenList.size() > 0) {
                                                    tbTokenId = tokenList.get(0);
                                                    TbToken tbToken = tbTokenMapper.selectById(tbTokenId, device_groupSendMsg.getMerId());
                                                    if(tbToken != null){
                                                        tbPid = tbToken.getDefPid();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            //中间页还为空，则从群管理配置的机器人身上获取
                            if(middlePageType == null || StringUtils.isBlank(middlePageUrl)){
                                if(configPlan == null){
                                    configPlan = configPlanMapper.selectById(device_groupSendMsg.getConfigId(), device_groupSendMsg.getMerId());
                                }
                                if(configPlan != null) {
                                    //淘宝插件id
                                    Long tbId = configPlan.getTbId();
                                    SysPlugin sysPlugin = sysPluginMapper.selectById(tbId, configPlan.getMerId());
                                    if (sysPlugin != null) {
                                        //淘宝token
                                        JSONObject jsonObject_tb = JSONObject.parseObject(sysPlugin.getData());
                                        if (jsonObject_tb != null) {
                                            middlePageType = jsonObject_tb.getInteger("middle_page_type");
                                            middlePageUrl = jsonObject_tb.getString("middle_page_url");
                                        }
                                    }
                                }
                            }

                            //京东平台
                            if(jdTokenId == null){
                                if(configPlan == null){
                                    configPlan = configPlanMapper.selectById(device_groupSendMsg.getConfigId(), device_groupSendMsg.getMerId());
                                }
                                if(configPlan != null){
                                    //京东token
                                    JSONObject jsonObject_jd = JSONObject.parseObject(configPlan.getJdAccountId());
                                    if(jsonObject_jd != null) {
                                        JSONArray jsonArray = jsonObject_jd.getJSONArray("tokens");
                                        if (jsonArray != null && jsonArray.size() > 0) {
                                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                                            String tokenIds = jsonObject.getString("tokenIds");
                                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                                            if (tokenList != null && tokenList.size() > 0) {
                                                jdTokenId = tokenList.get(0);
                                            }
                                        }
                                    }
                                }
                            }

                            //拼多多平台
                            if(pddTokenId == null){
                                //查询当前群内发送消息机器人
                                if(configPlan == null){
                                    configPlan = configPlanMapper.selectById(device_groupSendMsg.getConfigId(), device_groupSendMsg.getMerId());
                                }
                                if(configPlan != null){
                                    //拼多多token
                                    JSONObject jsonObject_pdd = null;
                                    pddTokenType = configPlan.getPddAccountType();
                                    if(pddTokenType != null && pddTokenType.intValue() == 1){ //推老板共享联盟
                                        jsonObject_pdd = JSONObject.parseObject(configPlan.getTlbPddAccountId());
                                    }else{ //拼多多联盟
                                        jsonObject_pdd = JSONObject.parseObject(configPlan.getPddAccountId());
                                    }
                                    if(jsonObject_pdd != null) {
                                        JSONArray jsonArray = jsonObject_pdd.getJSONArray("tokens");
                                        if (jsonArray != null && jsonArray.size() > 0) {
                                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                                            String tokenIds = jsonObject.getString("tokenIds");
                                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                                            if (tokenList != null && tokenList.size() > 0) {
                                                pddTokenId = tokenList.get(0);
                                            }
                                        }
                                    }
                                }
                            }

                            //唯品会平台
                            if(vphTokenId == null){
                                if(configPlan == null){
                                    configPlan = configPlanMapper.selectById(device_groupSendMsg.getConfigId(), device_groupSendMsg.getMerId());
                                }
                                if(configPlan != null){
                                    //唯品会token
                                    JSONObject jsonObject_vph = JSONObject.parseObject(configPlan.getVphAccountId());
                                    if(jsonObject_vph != null) {
                                        JSONArray jsonArray = jsonObject_vph.getJSONArray("tokens");
                                        if (jsonArray != null && jsonArray.size() > 0) {
                                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                                            String tokenIds = jsonObject.getString("tokenIds");
                                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                                            if (tokenList != null && tokenList.size() > 0) {
                                                vphTokenId = tokenList.get(0);
                                            }
                                        }
                                    }
                                }
                            }

                            //抖音平台
                            if(dyTokenId == null){
                                //查询当前群内发送消息机器人
                                if(configPlan == null){
                                    configPlan = configPlanMapper.selectById(device_groupSendMsg.getConfigId(), device_groupSendMsg.getMerId());
                                }
                                if(configPlan != null){
                                    //拼多多token
                                    JSONObject jsonObject_dy = null;
                                    dyTokenType = configPlan.getDyAccountType();
                                    if(dyTokenType != null && dyTokenType.intValue() == 1){ //推老板共享联盟
                                        jsonObject_dy = JSONObject.parseObject(configPlan.getTlbDyAccountId());
                                    }else{ //拼多多联盟
                                        jsonObject_dy = JSONObject.parseObject(configPlan.getDyAccountId());
                                    }
                                    if(jsonObject_dy != null) {
                                        JSONArray jsonArray = jsonObject_dy.getJSONArray("tokens");
                                        if (jsonArray != null && jsonArray.size() > 0) {
                                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                                            String tokenIds = jsonObject.getString("tokenIds");
                                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                                            if (tokenList != null && tokenList.size() > 0) {
                                                dyTokenId = tokenList.get(0);
                                            }
                                        }
                                    }
                                }
                            }

                            //封装发单采集群任务配置缓存对象
                            fdFollowGroupTaskCacheDto.setMerId(fdDevicePlanGroup.getMerId());
                            fdFollowGroupTaskCacheDto.setFdFollowGroupConfigId(fdFollowGroupConfig.getId());
                            fdFollowGroupTaskCacheDto.setIgnore(fdFollowGroupConfig.getIgnore());
                            fdFollowGroupTaskCacheDto.setTurnlink(fdFollowGroupConfig.getTurnlink());
                            fdFollowGroupTaskCacheDto.setLimitTimeStart(fdFollowGroupConfig.getLimitTimeStart());
                            fdFollowGroupTaskCacheDto.setLimitTimeEnd(fdFollowGroupConfig.getLimitTimeEnd());
                            fdFollowGroupTaskCacheDto.setImgSecret(fdFollowGroupConfig.getImgSecret());
                            fdFollowGroupTaskCacheDto.setEmoji(fdFollowGroupConfig.getEmoji());
                            fdFollowGroupTaskCacheDto.setFdDevicePlanId(fdDevicePlanGroup.getFdDevicePlanId());
                            fdFollowGroupTaskCacheDto.setGroupWxid(fdDevicePlanGroup.getWxid());
                            fdFollowGroupTaskCacheDto.setDeviceId(fdDevicePlanGroup.getDeviceId());
                            fdFollowGroupTaskCacheDto.setDeviceType(fdDevicePlanGroup.getDeviceType());
                            fdFollowGroupTaskCacheDto.setDeviceUniqueId(fdDevicePlanGroup.getDeviceUniqueId());
                            fdFollowGroupTaskCacheDto.setGroupSendDeviceUniqueId(fdDevicePlanGroup.getGroupSendDeviceUniqueId());
                            fdFollowGroupTaskCacheDto.setGroupSendDeviceId(device_groupSendMsg.getDeviceId());
                            fdFollowGroupTaskCacheDto.setTbTokenId(tbTokenId);
                            fdFollowGroupTaskCacheDto.setTbPid(tbPid);
                            fdFollowGroupTaskCacheDto.setTbRid(tbRid);
                            fdFollowGroupTaskCacheDto.setPwdpres(pwdpres);
                            fdFollowGroupTaskCacheDto.setPwdsufs(pwdsufs);
                            fdFollowGroupTaskCacheDto.setMiddlePageType(middlePageType);
                            fdFollowGroupTaskCacheDto.setMiddlePageUrl(middlePageUrl);
                            fdFollowGroupTaskCacheDto.setJdTokenId(jdTokenId);
                            fdFollowGroupTaskCacheDto.setPddTokenType(pddTokenType);
                            fdFollowGroupTaskCacheDto.setPddTokenId(pddTokenId);
                            fdFollowGroupTaskCacheDto.setPddTlbTokenId(pddTokenId);
                            fdFollowGroupTaskCacheDto.setVphTokenId(vphTokenId);
                            fdFollowGroupTaskCacheDto.setDyTokenType(dyTokenType);
                            fdFollowGroupTaskCacheDto.setDyTokenId(dyTokenId);
                            fdFollowGroupTaskCacheDto.setDyTlbTokenId(dyTokenId);
                            fdFollowGroupTaskCacheDtoList.add(fdFollowGroupTaskCacheDto);
                        }
                    }
                }
            }
        }

        //更新缓存
        String cacheKey = String.format(RedisCacheKeyEnum.FD_FOLLOW_GROUP_TASK_CACHE_KEY.getKey(), groupWxid);
        redisTemplate.opsForValue().set(cacheKey, JSONObject.toJSONString(fdFollowGroupTaskCacheDtoList));

    }


}
